package com.ning.activitys.skysound.fragment.mymusic;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.ning.activitys.skysound.R;
import com.ning.activitys.skysound.activity.MainActivity;
import com.ning.activitys.skysound.adpter.AllMusicAdapter;
import com.ning.activitys.skysound.base.BaseFragment;
import com.ning.activitys.skysound.base.MyApplication;
import com.ning.activitys.skysound.beans.MusicDetailsBeans;
import com.ning.activitys.skysound.service.PlayService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 16/1/16.
 */
public class RecentMusicFragment extends BaseFragment implements AdapterView.OnItemClickListener {

    private ListView listView;
    private AllMusicAdapter adapter;
    private ArrayList<MusicDetailsBeans> musicDetailsData;
    private MainActivity mainActivity;
    private MyApplication myApplication;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Log.e("onCreateView","----onCreateView");

        return inflater.inflate(R.layout.fragment_recent_music,null);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        myApplication = (MyApplication) mainActivity.getApplication();

        try {
            musicDetailsData = (ArrayList)myApplication.dbUtils.findAll(Selector.from(MusicDetailsBeans.class)
                    .where("playRecentTime", "!=", "0").orderBy("playRecentTime",true).limit(5));

        } catch (DbException e) {
            e.printStackTrace();
        }


        listView = (ListView) view.findViewById(R.id.list_view_recent_music);

        if(null == musicDetailsData || musicDetailsData.size() == 0){
            return;
        }

        adapter = new AllMusicAdapter(mainActivity,musicDetailsData);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        PlayService.IS_NET_MUSIC = 1;

        if (mainActivity.playService.getPlatList() != PlayService.RECENT_MISIC){

            mainActivity.playService.setPlatList(PlayService.RECENT_MISIC);
            mainActivity.playService.setMusicDetailsData(musicDetailsData);
        }

        mainActivity.playService.play(position);

    }
}
